<template>
  <div>
    <div class="fixed-header">
      <div class="header-actions">
        <h3>节点库</h3>
        <div class="buttons">
          <el-button v-if="!selectMode" type="primary" @click="addTemplateNode">新增节点模板</el-button>
          <el-button v-if="!selectMode" type="success" @click="exportTemplates">
            <el-icon><Download /></el-icon>
            导出模板
          </el-button>
          <el-button v-if="!selectMode" type="warning" @click="triggerImport">
            <el-icon><Upload /></el-icon>
            导入模板
          </el-button>
          <el-button v-if="selectMode" type="primary" @click="handleMultiSelect">
            确认选择
          </el-button>
          <input
            type="file"
            ref="fileInput"
            style="display: none"
            accept=".json"
            @change="importTemplates"
          >
        </div>
      </div>
      
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索节点模板..."
          clearable
        />
      </div>
    </div>
    
    <!-- 卡片布局 -->
    <div class="card-container">
      <el-checkbox-group class="card-container" v-model="selectedTemplateIds" @change="handleCheckboxChange">
        <el-card 
          v-for="template in filteredTemplates" 
          :key="template.id" 
          class="template-card"
          :class="{ 'card-selected': isSelected(template.id) }"
        >
          <template #header>
            <div class="card-header">
              <el-checkbox 
                v-if="selectMode" 
                :value="template.id"
                @click.stop
              ></el-checkbox>
              <span class="card-title">{{ template.name }}</span>
              <div class="card-type">{{ getNodeTypeName(template.type) }}</div>
            </div>
          </template>
          <div class="card-content">
            <div class="content-preview" v-if="getContentPreview(template).startsWith('<div')" v-html="getContentPreview(template)"></div>
            <div class="content-preview" v-else>{{ getContentPreview(template) }}</div>
            <div class="card-actions" v-if="!selectMode">
              <el-button size="small" @click="editTemplate(template)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteTemplate(template)">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-checkbox-group>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useNodeLibraryStore } from '../stores/nodeLibraryStore';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download, Upload } from '@element-plus/icons-vue';
import { nodeOptions } from '../stores/baseData';
import { marked } from 'marked';
import '../styles/markdown.css';

const props = defineProps({
  selectMode: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['addTemplateNode', 'editTemplate', 'select-templates', 'close']);
const store = useNodeLibraryStore();
const { templates } = storeToRefs(store);
const selectedTemplateIds = ref([]);
const selectedTemplates = ref([]);
const fileInput = ref(null);
const searchQuery = ref('');

const filteredTemplates = computed(() => {
  if (!searchQuery.value) {
    return templates.value;
  }
  const query = searchQuery.value.toLowerCase();
  return templates.value.filter(template => 
    template.name.toLowerCase().includes(query) || 
    template.description?.toLowerCase().includes(query) ||
    template.type.toLowerCase().includes(query)
  );
});

const handleCheckboxChange = (value) => {
  selectedTemplates.value = templates.value.filter(template => 
    selectedTemplateIds.value.includes(template.id)
  );
};

const isSelected = (id) => {
  return selectedTemplateIds.value.includes(id);
};

const handleMultiSelect = () => {
  if (selectedTemplates.value.length === 0) {
    ElMessage.warning('请至少选择一个节点');
    return;
  }
  emit('select-templates', selectedTemplates.value);
  clearSelection();
  emit('close');
};

const addTemplateNode = () => {
  emit('addTemplateNode');
};

const editTemplate = (template) => {
  emit('editTemplate', template);
};

const deleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm('确定要删除这个模板节点吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await store.deleteTemplate(template.id);
    ElMessage.success('删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const triggerImport = () => {
  fileInput.value.click();
};

const exportTemplates = () => {
  const data = JSON.stringify(templates.value, null, 2);
  const blob = new Blob([data], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'node-templates.json';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const importTemplates = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    const text = await file.text();
    const data = JSON.parse(text);
    
    if (!Array.isArray(data)) {
      throw new Error('无效的模板数据格式');
    }

    for (const template of data) {
      await store.addTemplate(template);
    }

    ElMessage.success('导入成功');
    fileInput.value.value = ''; // 清除文件选择
  } catch (error) {
    console.error('导入模板失败:', error);
    ElMessage.error('导入失败: ' + error.message);
    fileInput.value.value = ''; // 清除文件选择
  }
};

const getNodeTypeName = (type) => {
  const option = nodeOptions.find(opt => opt.value === type);
  return option ? option.label : type;
};

const getContentPreview = (template) => {
  if (!template.content) return '';
  
  let content = '';
  if (typeof template.content === 'string') {
    content = template.content;
  } else if (template.content.text) {
    content = template.content.text;
  } else {
    content = JSON.stringify(template.content);
  }
  
  // 限制内容长度
  const truncatedContent = content.length > 100 ? content.substring(0, 100) + '...' : content;
  
  // 检查内容是否可能是Markdown
  if (truncatedContent.includes('#') || truncatedContent.includes('```') || truncatedContent.includes('*')) {
    // 返回渲染后的HTML
    return `<div class="markdown-preview">${marked(truncatedContent)}</div>`;
  }
  
  return truncatedContent;
};

const clearSelection = () => {
  selectedTemplateIds.value = [];
  selectedTemplates.value = [];
};

onMounted(async () => {
  try {
    await store.fetchTemplates();
  } catch (error) {
    console.error('加载模板失败:', error);
    ElMessage.error('加载模板失败');
  }
});

defineExpose({
  clearSelection
});
</script>

<style scoped>
/* 添加一个固定定位的容器 */
.fixed-header {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 10;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 16px;
}

/* 调整现有的 header-actions 和 search-container 样式 */
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-top: 16px;
}

.buttons {
  display: flex;
  gap: 8px;
}

h3 {
  margin: 0;
}

.search-container {
  margin-top: 0;
  margin-bottom: 0;
}

.card-container {
  padding-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

/* 覆盖 Element UI 的默认样式 */
:deep(.el-checkbox-group) {
  font-size: 14px;
  line-height: normal;
}

/* 确保卡片内的文本正常显示 */
.template-card {
  width: 280px;
  flex: 0 0 auto;
  transition: all 0.3s;
  cursor: pointer;
  margin-bottom: 10px;
  font-size: 14px;
}

.template-card:hover {
  /* transform: translateY(-5px); */
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.card-selected {
  border: 2px solid #409EFF;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title {
  flex: 1;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.card-type {
  font-size: 12px;
  color: #909399;
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.content-preview {
  display: -webkit-box;
  -webkit-line-clamp: 5;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
  max-height: 6.2em;
  background-color: #f9f9f9;
  padding: 8px;
  border-radius: 4px;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

/* 确保对话框内容不会溢出 */
:deep(.el-dialog__body) {
  overflow-x: hidden;
}

.markdown-preview :deep(h1),
.markdown-preview :deep(h2),
.markdown-preview :deep(h3),
.markdown-preview :deep(h4),
.markdown-preview :deep(h5),
.markdown-preview :deep(h6) {
  margin-top: 0.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-preview :deep(p) {
  margin-top: 0;
  margin-bottom: 0.5em;
}

.markdown-preview :deep(code) {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27,31,35,0.05);
  border-radius: 3px;
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace;
}
</style>
